package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import student.*;

/**
 * Servlet implementation class InsertServlet
 */
@WebServlet("/InsertServlet")
public class InsertServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public InsertServlet() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		PrintWriter out = response.getWriter();
		DiskFileItemFactory factory = new DiskFileItemFactory();
		// 内存存储的最大值
		factory.setSizeThreshold(4096);

		// factory.setRepository(tempPath);

		ServletFileUpload upload = new ServletFileUpload(factory);
		// upload.setHeaderEncoding("utf-8");
		StudentDao sd = new StudentDao();
		Student s = new Student();
		String fieldname = null;
		String values = null;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		List<FileItem> list = null;
		try {
			list = upload.parseRequest(request);
		} catch (FileUploadException e) {
			e.printStackTrace();
		}
		for (FileItem f : list) {
			fieldname = f.getFieldName();
			out.print("表单元素名：" + fieldname);
			out.print("文件名：" + f.getName());
			out.print("是否是表单元素：" + f.isFormField());
			if (f.isFormField()) {
				values = f.getString("utf-8");
				out.print("，value=" + values);
				if (fieldname.equals("sname"))
					s.setSname(new String(values));
				else if (fieldname.equals("sex"))
					s.setSex(new String(values));
				else if (fieldname.equals("telephone"))
					s.setTelephone(new String(values));
				else if (fieldname.equals("qq"))
					s.setQq(new String(values));
				else if (fieldname.equals("wechat"))
					s.setWechat(new String(values));
				else if (fieldname.equals("gradeid"))
					s.setGradeId(Long.parseLong(new String(values)));
				else if (fieldname.equals("enterdate"))
					try {
						s.setEnterDate(sdf.parse(new String(values)));
					} catch (ParseException e) {
						e.printStackTrace();
					}
				else if (fieldname.equals("fromcity"))
					s.setFromcity(new String(values));
				else if (fieldname.equals("birthday"))
					try {
						s.setBirthday(sdf.parse(new String(values)));
					} catch (ParseException e) {
						e.printStackTrace();
					}
				else if (fieldname.equals("address"))
					s.setAddress(new String(values));
				else if (fieldname.equals("pass"))
					s.setPass(new String(values));
			} else {
				if (f.getSize() <= 0)
					continue;
				ServletContext application = this.getServletContext();
				String realpath = application.getRealPath("images");
				String fileName = UUID.randomUUID().toString();// Math.random();
				String houzhui = f.getName().substring(f.getName().lastIndexOf('.'));
				String newName = fileName + houzhui;// 保存的文件名
				s.setIdcardpath("images/" + newName);
				try {
					f.write(new java.io.File(realpath, newName));
				} catch (Exception e) {
					e.printStackTrace();
				}
				// f.write(new java.io.File("d:/"+f.getName()));
				out.print("<br/>文件保存了");
				// out.print("<img src='images/"+newName+"'/>");
			}
			out.print("<br/>");
		}
		int n = sd.add(s);
		if (n > 0) {
			out.println("<script>alert('添加成功');</script>");
		} else {
			out.println("<script>alert('重复添加，添加失败！');history.back();</script>");
		}
		out.print("<a href='SelectServlet'>返回主页</a>");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
